package com.meiyuetao.myt.purchase.web.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.security.AuthContextHolder;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.view.OperationResult;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Maps;
import com.meiyuetao.myt.core.constant.VoucherTypeEnum;
import com.meiyuetao.myt.core.service.VoucherNumGenerateService;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.finance.entity.TradeReceiptDetail;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.service.CommodityService;
import com.meiyuetao.myt.purchase.entity.PurchaseReturnOrder;
import com.meiyuetao.myt.purchase.entity.PurchaseReturnOrder.PurchaseReturnOrderStatusEnum;
import com.meiyuetao.myt.purchase.entity.PurchaseReturnOrderDetail;
import com.meiyuetao.myt.purchase.service.PurchaseReturnOrderService;
import com.meiyuetao.myt.purchase.service.SupplierService;
import com.meiyuetao.myt.stock.service.StockInOutService;
import com.meiyuetao.myt.stock.service.StorageLocationService;

@MetaData("采购订单")
public class PurchaseReturnOrderController extends MytBaseController<PurchaseReturnOrder, Long> {

    private final Logger logger = LoggerFactory.getLogger(PurchaseReturnOrderController.class);

    @Autowired
    private PurchaseReturnOrderService purchaseReturnOrderService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private StorageLocationService storageLocationService;

    @Autowired
    private VoucherNumGenerateService voucherNumGenerateService;

    @Autowired
    private StockInOutService stockInOutService;

    @Override
    protected BaseService<PurchaseReturnOrder, Long> getEntityService() {
        return purchaseReturnOrderService;
    }

    @Override
    protected void checkEntityAclPermission(PurchaseReturnOrder entity) {
        // TODO Add acl check code logic
    }

    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "purchaseReturnOrderDetails");
    }

    public String isDisallowChargeAgainst() {
        if (bindingEntity.getRedwordDate() != null) {
            return "已红冲";
        }
        if (bindingEntity.getDeliveryTime() != null) {
            return "已发货，不能红冲";
        }
        return null;
    }

    public HttpHeaders doRedword() {
        purchaseReturnOrderService.redword(bindingEntity);
        setModel(OperationResult.buildSuccessResult("红冲完成"));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders purchaseReturnOrderDetails() {
        List<PurchaseReturnOrderDetail> purchaseReturnOrderDetails = bindingEntity.getPurchaseReturnOrderDetails();
        if (BooleanUtils.toBoolean(getParameter("clone"))) {
            for (PurchaseReturnOrderDetail purchaseReturnOrderDetail : purchaseReturnOrderDetails) {
                purchaseReturnOrderDetail.resetCommonProperties();
            }
        }
        setModel(buildPageResultFromList(purchaseReturnOrderDetails));
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    public Map<String, Object> getTaskVariables() {
        Map<String, Object> variables = taskService.getVariables(this.getRequiredParameter("taskId"));
        if (logger.isDebugEnabled()) {
            for (Map.Entry<String, Object> me : variables.entrySet()) {
                logger.debug("{} - {}", me.getKey(), me.getValue());
            }
        }
        return variables;
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        if (bindingEntity.isNew()) {
            List<PurchaseReturnOrderDetail> purchaseReturnOrderDetails = bindingEntity.getPurchaseReturnOrderDetails();
            for (PurchaseReturnOrderDetail purchaseReturnOrderDetail : purchaseReturnOrderDetails) {
                purchaseReturnOrderDetail.setPurchaseReturnOrder(bindingEntity);
            }
        }
        return super.doSave();
    }

    @MetaData("采购退货单创建初始化")
    public HttpHeaders bpmNew() {
        return buildDefaultHttpHeaders("bpmInput");
    }

    public void prepareBpmNew() {
        String clone = this.getParameter("clone");
        if (BooleanUtils.toBoolean(clone)) {
            bindingEntity.resetCommonProperties();
        } else {
            bindingEntity = new PurchaseReturnOrder();
        }
        bindingEntity.setVoucher(voucherNumGenerateService.getVoucherNumByType(VoucherTypeEnum.CGTH));
        bindingEntity.setVoucherDate(new Date());
        bindingEntity.setVoucherUser(getLogonUser());
        bindingEntity.setVoucherDepartment(getLogonUser().getDepartment());

    }

    @MetaData("采购退货单保存")
    public HttpHeaders bpmSave() {
        Map<String, Object> variables = Maps.newHashMap();
        String submitToAudit = this.getParameter("submitToAudit");
        if (BooleanUtils.toBoolean(submitToAudit)) {// 是否勾选 立即提交审核
            bindingEntity.setLastOperationSummary(bindingEntity.buildLastOperationSummary("提交"));
            bindingEntity.setSubmitDate(new Date());
        }

        for (PurchaseReturnOrderDetail prd : bindingEntity.getPurchaseReturnOrderDetails()) {
            prd.setPurchaseReturnOrder(bindingEntity);
        }

        if (bindingEntity.isNew()) {
            if (StringUtils.isBlank(bindingEntity.getTitle())) {
                List<PurchaseReturnOrderDetail> orderDetails = bindingEntity.getPurchaseReturnOrderDetails();
                Commodity commodity = commodityService.findOne(orderDetails.get(0).getCommodity().getId());
                String commodityTitle = commodity.getTitle();
                commodityTitle = StringUtils.substring(commodityTitle, 0, 30);
                bindingEntity.setTitle(commodityTitle + "...等" + orderDetails.size() + "项商品");
            }
            purchaseReturnOrderService.bpmCreate(bindingEntity, variables);
            setModel(OperationResult.buildSuccessResult("采购退货单创建完成，并同步启动处理流程", bindingEntity));
        } else {
            purchaseReturnOrderService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
            setModel(OperationResult.buildSuccessResult("采购退货单任务提交完成", bindingEntity));
        }
        return buildDefaultHttpHeaders();
    }

    @MetaData("一线审核")
    public HttpHeaders bpmLevel1Audit() {
        Map<String, Object> variables = Maps.newHashMap();
        variables.put("auditLevel1Time", new Date());
        variables.put("auditLevel1User", AuthContextHolder.getAuthUserPin());
        Boolean auditLevel1Pass = new Boolean(getRequiredParameter("auditLevel1Pass"));
        variables.put("auditLevel1Pass", auditLevel1Pass);
        variables.put("auditLevel1Explain", getParameter("auditLevel1Explain"));
        bindingEntity.setLastOperationSummary(bindingEntity.buildLastOperationSummary("审核"));
        if (!auditLevel1Pass) {
            bindingEntity.setSubmitDate(null);
        }
        purchaseReturnOrderService.bpmLevel1Audit(bindingEntity, this.getRequiredParameter("taskId"), variables);
        setModel(OperationResult.buildSuccessResult("采购退货单一线审核完成", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    @MetaData("寄出货物")
    public HttpHeaders bpmSendGoods() {
        Map<String, Object> variables = Maps.newHashMap();

        // TODO 寄出商品后 应扣减库存
        purchaseReturnOrderService.handleStockQuantity(bindingEntity);

        // TODO 寄出商品后 记账 （应收账款）
        purchaseReturnOrderService.handleAccountInOut(bindingEntity);

        bindingEntity.setDeliveryTime(new Date());
        bindingEntity.setReturnOrderStatus(PurchaseReturnOrderStatusEnum.S50EX);// 状态变为已寄出
        purchaseReturnOrderService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
        setModel(OperationResult.buildSuccessResult("采购退货单商品寄出完成", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    @MetaData("确认收货")
    public HttpHeaders bpmConfirmedReturn() {
        Map<String, Object> variables = Maps.newHashMap();

        bindingEntity.setReturnOrderStatus(PurchaseReturnOrderStatusEnum.S50EX);// 状态变为已确认收货
        purchaseReturnOrderService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
        setModel(OperationResult.buildSuccessResult("采购退货单确认退货完成", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    private List<TradeReceiptDetail> tradeReceiptDetails = new ArrayList<TradeReceiptDetail>();

    @MetaData("创建收款单")
    public HttpHeaders bpmCreateReceivablesReceipt() {
        Map<String, Object> variables = Maps.newHashMap();
        purchaseReturnOrderService.bpmCreateReceivablesReceipt(bindingEntity, this.getRequiredParameter("taskId"), tradeReceiptDetails);
        bindingEntity.setReturnOrderStatus(PurchaseReturnOrderStatusEnum.S65RECVE);// 状态变为已收款
        purchaseReturnOrderService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
        setModel(OperationResult.buildSuccessResult("采购退货单确认收货完成", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    public List<TradeReceiptDetail> getTradeReceiptDetails() {
        return tradeReceiptDetails;
    }

    public void setTradeReceiptDetails(List<TradeReceiptDetail> tradeReceiptDetails) {
        this.tradeReceiptDetails = tradeReceiptDetails;
    }

}